package com.easy.controller;

import com.easy.bean.User;
import com.easy.service.LoginService;
import com.easy.util.CaptchaUtil;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
    @Autowired
    LoginService loginService;

    //获取验证码
    @GetMapping("/captcha")
    public Result captcha() {
        return Result.success(CaptchaUtil.getCaptcha());
    }

    //登录
    @PostMapping("/dologin")
    public Result login(User user,  // 绑定前端传递的 user 参数
                        @RequestParam("captcha") String captcha,  // 绑定验证码
                        @RequestParam("key") String key) {
        //1.验证验证码
        if (!CaptchaUtil.checkCaptcha(key, captcha)) {
            return Result.fail(500,"验证码错误");
        }
        //2.登录
        try {
            String token = loginService.login(user);
            //删除验证码
            return Result.success("登录成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,"登录异常");
        }
    }

    //获取登录信息
    @GetMapping("/logininfo")
    public Result logininfo(HttpServletRequest request, HttpSession session){
        //拿到令牌
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);

        if (token == null) {
            return Result.fail(401, "认证失败，Token 无效");
        }
        //验证令牌
        User user = loginService.logininfo(token);
        return Result.success(user);

    }
}
